package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.Builder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    @Override
    @Transactional  // 涉及到多张表的增删改，要开启事务
    public void addDish(DishDTO dishDTO) {
        // 1、构造菜品基本信息数据，将其存入dish表中
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.insert(dish);

        log.info("dishID = {}", dish.getId());

        // 2、构造菜品口味数据，将其存入dish_flavor表中
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && !flavors.isEmpty()) {
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dish.getId());
            });
            //向口味表插入n条数据
            dishFlavorMapper.insertDishFlavor(flavors);//后绪步骤实现
        }
    }

    @Override
    public PageResult getDishPage(DishPageQueryDTO dishDTO) {
        PageHelper.startPage(dishDTO.getPage(), dishDTO.getPageSize());
        Page<DishVO> pages = dishMapper.getDishPage(dishDTO);
        return new PageResult(pages.getTotal(), pages.getResult());
    }

    @Override
    @Transactional
    public void deleteDish(List<Long> ids) {
        List<Dish> dishes = dishMapper.selectDishById(ids);
        // 1、判断该菜品是否起售，如果起售，则不能删除
        dishes.forEach(dish -> {
            if (dish.getStatus() == StatusConstant.ENABLE) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        });
        // 2、判断菜品是否被套餐关联，如果被套餐关联，则不能删除
        Integer count = setmealDishMapper.countByDishId(ids);
        if (count > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        // 3、删除菜品基本表
        dishMapper.deleteDish(ids);

        // 4、删除菜品口味表
        dishFlavorMapper.deleteDishFlavorByDishId(ids);
    }

    @Override
    public DishVO getDishById(Long id) {
        // 1、根据Id查菜品
        Dish dish = dishMapper.getDishById(id);
        // 2、根据Id查菜品口味
        List<DishFlavor> dishFlavor = dishFlavorMapper.getDishFlavorByDishId(id);
        // 3、组装返回值
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(dishFlavor);
        return dishVO;
    }

    @Override
    @Transactional
    public void updateDish(DishDTO dishDTO) {
        // 1、修改菜品基本信息
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.updateDish(dish);
        // 2、修改菜品口味信息
        // 由于口味列表可能增加，可能删除，可能修改，因此需要先删除原有的口味，再插入新的口味
        dishFlavorMapper.delete(dishDTO.getId());

        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && !flavors.isEmpty()) {
            // 关联菜品Id
            flavors.forEach(flavor -> {
                flavor.setDishId(dishDTO.getId());
            });
            dishFlavorMapper.insertDishFlavor(flavors);
        }
    }

    @Override
    @Transactional
    public void updateDishStatus(String status, Long id) {
        // 如果不封装为对象，那么就无法修改UpdateTime和UpdateUser字段了
        Dish dish = Dish.builder()
                .id(id)
                .status(Integer.parseInt(status))
                .build();
        dishMapper.updateDish(dish);
        if (Integer.parseInt(status) == StatusConstant.DISABLE) {
            // 如果是停售操作，还需要将包含当前菜品的套餐也停售
            List<Long> dishIds = new ArrayList<>();
            dishIds.add(id);
            List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(dishIds);
            setmealIds.forEach(setmealId -> {
                Setmeal setmeal = Setmeal.builder()
                        .id(setmealId)
                        .status(StatusConstant.DISABLE)
                        .build();
                setmealMapper.update(setmeal);
            });
        }
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getDishFlavorByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

    @Override
    public List<Dish> getDishByCategoryId(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.getDishByCategoryId(dish);
    }
}
